package com.cwh.taskcenter.domain.engine.rule.parser;

import io.micrometer.common.util.StringUtils;

import java.util.List;

/**
 * @author cwh
 */
public class ConditionTreeParser {

    public static String parseConditionTree(ConditionTree node) {
        if (node == null) return "false";

        // 处理逻辑节点 (AND/OR)
        if (node.getChildren() != null && !node.getChildren().isEmpty()) {
            return handleLogicalNode(node);
        }
        // 处理叶子节点
        else {
            return handleLeafNode(node);
        }
    }

    // 处理逻辑节点 (AND/OR)
    private static String handleLogicalNode(ConditionTree node) {
        String operator = node.getOperator();
        if (StringUtils.isBlank(operator)) {
            throw new RuntimeException("Unsupported logical operator: " + operator);
        }
        operator = operator.toUpperCase();

        List<ConditionTree> children = node.getChildren();
        StringBuilder sb = new StringBuilder();
        sb.append("(");

        for (int i = 0; i < children.size(); i++) {
            if (i > 0) {
                sb.append(operator).append(" ");
            }
            sb.append(parseConditionTree(children.get(i)));
        }

        sb.append(")");
        return sb.toString();
    }

    // 处理叶子节点（字段比较）
    private static String handleLeafNode(ConditionTree node) {
        String field = node.getFieldName();
        String operator = node.getOperator();
        String value = node.getValue();
        String executionFuncName = node.getExecutionFuncName();

        // 建议在此处加入字段白名单校验、SQL 转义等逻辑
        // 示例：防止字段名为 SQL 关键字
        if ("OR".equalsIgnoreCase(field) || "AND".equalsIgnoreCase(field)) {
            throw new IllegalArgumentException("Invalid field name: " + field);
        }
        if (StringUtils.isNotBlank(executionFuncName)) {
            return executionFuncName+"( " + value + " )";
        }

        return field + " " + operator + " " + value + " ";
    }

}
